package com.awenhui.demo.controller;

import com.awenhui.demo.config.shiro.PhoneVcodeToken;
import com.awenhui.demo.config.shiro.UserDto;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author yuxf
 * @version 1.0
 * @date 2020/12/21 17:37
 */
@RestController
@RequestMapping("/shiro")
public class ShiroController {

    /**
     * 登录
     *
     * @return
     */
    @GetMapping("/login")
    public String login() {

        Subject subject = SecurityUtils.getSubject();
        subject.login(new UsernamePasswordToken("admin", "123456"));
        return "登录成功";

    }

    @GetMapping("/phoneLogin")
    public String phoneLogin(String phone, String vcode) {
        Subject subject = SecurityUtils.getSubject();
        try {
            subject.login(new PhoneVcodeToken(phone, vcode));
            return "登录成功";
        } catch (Exception ex) {
            return "登录失败：" + ex.getClass().getName() + "," + ex.getMessage();
        }
    }

    @GetMapping({"", "/index"})
    public Object index() {
        UserDto userDto = (UserDto) SecurityUtils.getSubject().getPrincipal();

        return userDto;
    }

    @GetMapping("/user")
    @RequiresPermissions("user:list")
    public Object user() {
        UserDto userDto = (UserDto) SecurityUtils.getSubject().getPrincipal();

        return userDto;
    }

    @GetMapping("/anon")
    public String anon() {
        return "可以匿名访问页面";
    }
}
